﻿using System;
using System.Collections.Generic;
using System.Text;
using WAD.Model;
using System.Data;

namespace WAD.DAL.Union
{
    public class DAOAgent : DAO_Union
    {
        public static int Add(int user_id, string sitename, string phone, string mobile, string email, string linkman, string endtime)
        {
            string sql = "insert into vifo_users_agent(userid_wjx,UserID,CompanyName,Phone,CellPhone,Email,Linkman,JoinTime,Expiration_wjx,UpdateTime,status,Deleted)values";
            sql += string.Format("({0},{1},'{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')", user_id, 0, sitename, phone, mobile, email, linkman, DateTime.Now.ToString(), endtime, DateTime.Now.ToString(), 4, 0);
            return ExecuteNonQuery(sql);
        }

        public static Dictionary<string, object> Get(int id)
        {
            Dictionary<string, object> dic = Get("vifo_users_agent", "userid_wjx=" + id, "userid,balance,price,products,CompanyName as sitename,Expiration_wjx as endtime,JoinTime as addtime");
            if (dic == null || dic["price"] == DBNull.Value) return null;
            System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
            xml.LoadXml(dic["price"].ToString());
            System.Xml.XmlNode item = xml.SelectSingleNode("root/items[@id=\"5\"]");    //id: 1 商汇通, 3 微推广, 4 微网站 ,5是微街秀
            //折扣
            if (item == null || item.InnerXml == null)
                dic["discount"] = 0;
            else
            {
                dic["discount"] = item.ChildNodes[0].Attributes["discount"].InnerText;
            }

            //代理组
            if (dic["products"] != DBNull.Value)
            {
                //5=&12=&11=60
                Dictionary<string, string> version = new Dictionary<string, string>();
                string[] arr = dic["products"].ToString().Split('&');
                for (int i = 0; i < arr.Length; i++)
                {
                    string[] arrItem = arr[i].Split('=');
                    if (!string.IsNullOrEmpty(arrItem[1]))
                        version.Add(arrItem[0], arrItem[1]);
                }
                if (version.Count > 0)
                    dic["version"] = version; //版本列表
            }
            dic.Remove("products");
            dic.Remove("price");
            return dic;
        }

        /// <summary>
        /// 更新余额
        /// </summary>
        /// <param name="agentid"></param>
        /// <param name="price"></param>
        /// <returns></returns>
        public static int UpdateBalance(int agentid, Decimal price, int unionid = 0)
        {
            int count = ExecuteNonQuery(string.Format("update vifo_users_agent set balance={0} where userid_wjx={1}", price, agentid));
            if (unionid > 0)
                ExecuteNonQuery(string.Format("update vifo_users set UserMoney={0} where userid={1}", price, unionid));
            return count;
        }

        /// <summary>
        /// 刷新用户表，代理商表的金额
        /// </summary>
        /// <param name="p_balance"></param>
        /// <param name="unionid"></param>
        /// <returns></returns>
        public static object RefrushBalance(object p_balance, int unionid)
        {
            Dictionary<string, object> dic = Get("vifo_users", "userid=" + unionid, "usermoney");
            if (dic == null || p_balance == DBNull.Value)
                return p_balance;

            Decimal balance = Convert.ToDecimal(p_balance);
            Decimal balance2 = Convert.ToInt32(dic["usermoney"]);
            
            if (balance > balance2)
            {
                ExecuteNonQuery(string.Format("update vifo_users_agent set balance={0} where userid={1}", balance2, unionid));
                return balance2;
            }
            else if (balance < balance2)
            {
                ExecuteNonQuery(string.Format("update vifo_users set usermoney={0} where userid={1}", balance, unionid));
                return balance;
            }
            return balance;
        }


        public static PageData GetPageList(string fields, string where, int pageIndex, int pageSize)
        {
            PageData pageData = new PageData();
            if (!string.IsNullOrEmpty(where))
                where = " where " + where;

            DataTable dt = DAO_Union.ExecuteDataTable(string.Format("select top {0} {1} from vifo_users_agent {2}", pageSize, fields, where));

            int total = (int)DAO_Union.ExecuteScalar(string.Format("select count(1) from vifo_users_agent {0}", where));

            int itemCount = total;
            int pageCount = itemCount / pageSize;

            pageData.table = dt;
            pageData.pageSize = pageSize;
            pageData.pageIndex = pageIndex;
            pageData.pageCount = pageCount; //总页数
            pageData.itemCount = itemCount; //数据总条数
            return pageData;
        }
    }
}
